package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.LongController;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 用户提交订单
     *
     * @param ordersSubmitDTO 订单信息
     * @return 返回信息
     * 业务分析:
     *      1.先判断有没有地址信息,没有抛异常
     *      2.在判断有没有商品信息,没有抛异常
     *      3.保存订单信息到订单表
     *      4.保存订单详情到订单详情表
     *      5.返回前端需要的数据
     */
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //1.先判断有没有地址信息,没有抛异常
        AddressBook addressBook = addressBookMapper.findById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //2.在判断有没有商品信息,没有抛异常
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findByUserId(userId);
        if (shoppingCartList == null || shoppingCartList.size() == 0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //3.保存订单信息到订单表
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //生成订单号
        orders.setNumber(System.currentTimeMillis() + userId + "");
        //设置状态为带付款
        orders.setStatus(Orders.PENDING_PAYMENT);
        //设置下单用户
        orders.setUserId(userId);
        //设置下单时间
        orders.setOrderTime(LocalDateTime.now());
        //设置支付状态
        orders.setPayStatus(Orders.UN_PAID);
        //设置手机号
        orders.setPhone(addressBook.getPhone());
        //拼接地址信息
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //设置收货人
        orders.setConsignee(addressBook.getConsignee());
        //3.保存订单信息到订单表,并且返回主键
        ordersMapper.add(orders);
        //4.保存订单详情到订单详情表
        shoppingCartList.forEach(shoppingCart->{
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            //这里需要把复制过来的id清掉
            orderDetail.setId(null);
            //设置订单返回的主键id
            orderDetail.setOrderId(orders.getId());
            //把订单详情保存到表中
            orderDetailMapper.add(orderDetail);
        });
        //5.返回前端需要的数据
        return OrderSubmitVO.builder()
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .id(orders.getId())
                .build();
    }

    /**
     * 支付成功会修改订单
     *
     * @param orderNum
     */
    @Override
    public void paySuccess(String orderNum) {
        //根据订单号查询订单
        Orders orders = ordersMapper.findByOrderNum(orderNum);
        Orders paidOrders = Orders.builder().id(orders.getId())
                //支付状态给成已支付
                .payStatus(Orders.PAID)
                //订单状态改成待接单
                .status(Orders.TO_BE_CONFIRMED)
                //设置支付时间
                .checkoutTime(LocalDateTime.now())
                .build();
        ordersMapper.update(paidOrders);
    }

    /**
     * 退款成功
     * @param orderNum
     */
    @Override
    public void refundSuccess(String orderNum) {
        //退款成功之后要把订单支付状态改成退款
        Orders orders = ordersMapper.findByOrderNum(orderNum);
        Orders refund = Orders.builder()
                .payStatus(Orders.REFUND)
                .id(orders.getId())
                .build();
        ordersMapper.update(refund);
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderDetailVO selectOrderDetail(Integer id) {
        //根据订单id查询订单
        OrderDetailVO vo=ordersMapper.selectOrderById(id);
        //根据订单id查询订单详情列表
        List<OrderDetail> orderDetailList=ordersMapper.selectOrderDetailById(id);
        vo.setOrderDetailList(orderDetailList);
        return vo;
    }

    /**
     * 接单
     * @param
     */
    @Override
    public void confirm(LongController longController) {
        longController.setStatus(Orders.CONFIRMED);
        ordersMapper.confirm(longController);
    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //根据条件查询订单信息
        Page<Orders> page = ordersMapper.findByCondition(ordersPageQueryDTO);
        //获取查询后的订单信息
        List<Orders> ordersList = page.getResult();
        //查询到的订单信息有数据
        if (ordersList != null && ordersList.size() > 0) {
            //封装OrdersConditionSearchVO
            List<OrdersConditionSearchVO> collect = ordersList.stream().map(orders -> {
                OrdersConditionSearchVO ordersConditionSearchVO = new OrdersConditionSearchVO();
                BeanUtils.copyProperties(orders, ordersConditionSearchVO);
                //根据订单id查询订单详细信息
                List<OrderDetail> orderDetailList = orderDetailMapper.findByOrderId(orders.getId());
                //查询到的订单详细信息有数据
                if (orderDetailList != null && orderDetailList.size() > 0) {
                    //封装订单详细信息中菜品的名字
                    List<String> nameList = orderDetailList.stream().map(orderDetail -> orderDetail.getName()).collect(Collectors.toList());
                    ordersConditionSearchVO.setOrderDishes(nameList.toString());
                }
                return ordersConditionSearchVO;
            }).collect(Collectors.toList());
            return new PageResult(page.getTotal(), collect);
        }
        List<OrdersConditionSearchVO> list = new ArrayList<>();
        return new PageResult(page.getTotal(), list);
    }

    /**
     * 修改订单状态为派送状态
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //查询订单信息
        Orders orders = ordersMapper.findById(id);
        //修改订单状态为派送状态
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersMapper.delivery(orders);
    }

    /**
     * 根据订单id修改状态为完成和完成时间
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        //查询订单信息
        Orders orders = ordersMapper.findById(id);
        //修改订单状态为完成状态
        orders.setStatus(Orders.COMPLETED);
        //修改订单完成时间
        orders.setDeliveryTime(LocalDateTime.now());
        //根据订单id修改状态为完成和完成时间
        ordersMapper.delivery(orders);
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Transactional
    @Override
    public void cancel(Long id) {
        Long currentId = BaseContext.getCurrentId();
        Orders orders = new Orders();
        orders.setId(id);
        orders.setUserId(currentId);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.cancel(orders);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        List<OrderDetail> byOrderId = orderDetailMapper.findByOrderId(id);
        Orders byId1 = ordersMapper.findById(id);
        Long userId = byId1.getUserId();
        Employee employee = employeeMapper.findById(Math.toIntExact(userId));
        String name = employee.getName();
        byOrderId.forEach(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setId(null);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setUserId(userId);
            shoppingCart.setName(orderDetail.getName());
            shoppingCartMapper.add(shoppingCart);
        });
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        List<Integer> statusList = ordersMapper.findStatus();
        if (statusList != null && statusList.size() > 0) {
            OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
            for (Integer integer : statusList) {
                switch (integer) {
                    //待接单
                    case 2:
                        orderStatisticsVO.setToBeConfirmed((orderStatisticsVO.getToBeConfirmed() == null ? 0 : orderStatisticsVO.getToBeConfirmed()) + 1);
                        break;
                    //待派送
                    case 3:
                        orderStatisticsVO.setConfirmed((orderStatisticsVO.getConfirmed() == null ? 0 : orderStatisticsVO.getConfirmed()) + 1);
                        break;
                    //派送中
                    case 4:
                        orderStatisticsVO.setDeliveryInProgress((orderStatisticsVO.getDeliveryInProgress() == null ? 0 : orderStatisticsVO.getDeliveryInProgress()) + 1);
                        break;
                }
            }
            return orderStatisticsVO;
        }
        return null;
    }

    /**
     * 订单详情查询
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetailToClear(Long id) {
        Orders orders = ordersMapper.findById(id);
        List<OrderDetail> list = orderDetailMapper.findByOrderId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(list);
        return orderVO;
    }

    /**
     * 查询历史订单
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Long userId = BaseContext.getCurrentId();
        //根据userId和状态查询订单
        List<Orders> list = ordersMapper.searchHistory(ordersPageQueryDTO.getStatus(),userId);
        PageInfo<Orders> pageInfo = new PageInfo<>(list);
        List<OrdersHistoryVO> voList = list.stream().map(orders -> {
            //根据订单号查询商品详情
            List<OrderDetail> orderDetailList = orderDetailMapper.findByOrderId(orders.getId());
            OrdersHistoryVO ordersHistoryVO = new OrdersHistoryVO();
            BeanUtils.copyProperties(orders, ordersHistoryVO);
            ordersHistoryVO.setOrderDetailList(orderDetailList);
            return ordersHistoryVO;
        }).collect(Collectors.toList());
        return new PageResult(pageInfo.getTotal(),voList);
    }

    /**
     * ordersPaymentDTO
     * @param ordersPaymentDTO
     */
    @Override
    public void payment(OrdersPaymentDTO ordersPaymentDTO) {
        //先根据订单号查询订单信息
        Orders orders = ordersMapper.findByOrderNum(ordersPaymentDTO.getOrderNumber());
        //2.3步无法完成,只能模拟一下
        //4.清空购物车
        Long userId = BaseContext.getCurrentId();
        shoppingCartMapper.delByUserId(userId);
    }
}
